package com.zx.sdk.league.member.baidu

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import com.baidu.mobads.sdk.api.CPUWebAdRequestParam
import com.baidu.mobads.sdk.api.CpuAdView
import com.baidu.mobads.sdk.api.CpuLpFontSize
import java.util.*


class BaiduFragment : Fragment() {
    private var _isHidden = false
    private var mCpuView: CpuAdView? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return FrameLayout(inflater.context)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 推荐媒体获取outerId的方式
        val outerId: String = UUID.randomUUID().toString()
            .replace("-", "")
            .substring(0, 16)
        val cpuWebAdRequestParam = CPUWebAdRequestParam.Builder()
            .setLpFontSize(CpuLpFontSize.REGULAR)
            .setLpDarkMode(true)
            .setCustomUserId(outerId)
            .build()
        // 小视频频道的内容
        mCpuView = CpuAdView(view.context, arguments?.getString("appId"), 1094, cpuWebAdRequestParam)
        (view as ViewGroup).addView(mCpuView, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        // 考虑到媒体在 锁屏开关等场景下 有刷新页面的需求，SDK目前将控件的创建与
        // 数据的请求进行拆分，媒体在已创建控件的前提下，可以直接调用下面这行代码来请求或着更新数据
        mCpuView?.requestData()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            mCpuView?.onResume()
        } else {
            mCpuView?.onPause()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        _isHidden = hidden
        if (!hidden && userVisibleHint) {
            mCpuView?.onResume()
        } else {
            mCpuView?.onPause()
        }
    }

    override fun onResume() {
        super.onResume()
        if (userVisibleHint && !_isHidden) {
            mCpuView?.onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        mCpuView?.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mCpuView?.onDestroy()
    }
}